#!/usr/bin/python
##
# trac-news
#
# Author: Miguel Angel Garcia
# Licence: MIT Licence
##

import feedparser
import pynotify
import time
from datetime import datetime
import sys

def usage():
  print "\n Usage: " + sys.argv[0] + " URL_TRAC\n Ej: " + sys.argv[0] + " http://example.org/trac/\n"

def getUltimaNovedad():
  """
  Retorna la  ultima novedad del timeline del dia actual o None si no hay ninguna.
  El resultado es un {} con los campos: time, author, title, tipo y summary.
  """
  url = URL_TRAC + 'timeline?ticket=on&changeset=on&max=1&daysback=0&format=rss'
  feed = feedparser.parse(url)
  if len(feed['items']) == 0: return None
  novedad = {}
  novedad['time'] = feed['items'][0]['updated_parsed']
  novedad['author'] = feed['items'][0]['author']
  novedad['title'] =  feed['items'][0]['title_detail']['value']
  novedad['tipo'] = feed['items'][0]['tags'][0]['term']
  novedad['summary'] = feed['items'][0]['summary']
  novedad['href'] = feed['items'][0]['links'][0]['href']
  return novedad


def main():
  if(len(sys.argv) < 2):
    return usage()
  global URL_TRAC
  URL_TRAC = sys.argv[1]
  pynotify.init("cli notify")

  novedad = getUltimaNovedad()
  if novedad is None: lastUpdate = 0
  else: lastUpdate = novedad['time']

  pynotify.Notification("trac-news up and running :)").show()
  # Obtener ultima novedad y mostrar notificacion.
  while(True):
    novedad = getUltimaNovedad()
    if((novedad is not None) and (novedad['time'] != lastUpdate)):
      lastUpdate = novedad['time']
      link = "<a href='" + novedad['href'] + "'>Go</a>"
      if novedad['tipo'] == 'changeset':
        n = pynotify.Notification(novedad['title'] + ' by ' + novedad['author'], link)
      else: # Cambio en un ticket
        n = pynotify.Notification(novedad['title'] + ' by ' + novedad['author'], novedad['summary'] + " " + link)
      n.show()
    else:
      time.sleep(3)

if __name__ == '__main__':
  main()
